/*
 * @(#)QqaiPlugin.java 2020年3月9日 上午10:56:30
 * Copyright 2020 zmr, Inc. All rights reserved. 
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.wind.cqboot.plugin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wind.cqboot.utils.HttpUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import net.lz1998.cq.event.message.CQGroupMessageEvent;
import net.lz1998.cq.robot.CQPlugin;
import net.lz1998.cq.robot.CoolQ;
import net.lz1998.cq.utils.CQCode;

/**
 * <p>File：QqaiPlugin.java</p>
 * <p>Title: </p>
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2020 2020年3月9日 上午10:56:30</p>
 * <p>Company: zmrit.com </p>
 * @author zmr
 * @version 1.0
 */
@Component
public class QqaiPlugin extends CQPlugin
{
    private static final String REQUEST_URL = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat";

    @Override
    public int onGroupMessage(CoolQ cq, CQGroupMessageEvent event)
    {
        String msg = event.getMessage();
        Long groupId = event.getGroupId();
        Long userId = event.getUserId();
        if (msg.contains(CQCode.at(cq.getSelfId())))
        {
            msg = msg.replace(CQCode.at(cq.getSelfId()) + " ", "");
            String content = buildReply(userId, msg);
            if (null != content)
            {
                String result = CQCode.at(userId) + " " + content;
                cq.sendGroupMsg(groupId, result, false);
                return MESSAGE_BLOCK;
            }
            // 继续执行下一个插件
            return MESSAGE_IGNORE;
        }
        // 继续执行下一个插件
        return MESSAGE_IGNORE;
    }

    @Value("${qq.ai.appkey}")
    private String appkey;

    @Value("${qq.ai.appid}")
    private String appid;

    public String buildReply(long userId, String question)
    {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("time_stamp", DateUtil.currentSeconds());
        params.put("nonce_str", IdUtil.simpleUUID());
        params.put("session", userId);
        params.put("question", question);
        params.put("app_id", appid);
        String sign = getSing(params);
        params.put("sign", sign);
        String result = HttpUtil.sendGet(REQUEST_URL, MapUtil.join(params, "&", "="));
        JsonObject json = JsonParser.parseString(result).getAsJsonObject();
        if (json.get("ret").getAsInt() == 0)
        {
            return json.getAsJsonObject("data").get("answer").getAsString();
        }
        return null;
    }

    /**
     * 计算步骤
     * 1.将<key, value>请求参数对按key进行字典升序排序，得到有序的参数对列表N
     * 2.将列表N中的参数对按URL键值对的格式拼接成字符串，得到字符串T（如：key1=value1&key2=value2），URL键值拼接过程value部分需要URL编码，URL编码算法用大写字母，例如%E8，而不是小写%e8
     * 3.将应用密钥以app_key为键名，组成URL键值拼接到字符串T末尾，得到字符串S（如：key1=value1&key2=value2&app_key=密钥)
     * 4.对字符串S进行MD5运算，将得到的MD5值所有字符转换成大写，得到接口请求签名
     * @param params
     * @return
     * @author zmr
     */
    private String getSing(Map<String, Object> params)
    {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < keys.size(); i++)
        {
            String key = keys.get(i);
            Object value = params.get(key);
            sb.append(key + "=" + value + "&");
        }
        sb.append("app_key=").append(appkey);
        String md5Str = URLUtil.encode(sb.toString());
        return SecureUtil.md5(md5Str).toUpperCase();
    }
}
